﻿#include "csvProcessApi.h"

#include "csv.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>

CSV_API void csvToBin(const std::string& csvFilename, const std::string& binFilename)
 {
    io::CSVReader<3> csv(csvFilename);
    csv.read_header(io::ignore_extra_column, "Name", "Age", "Salary");

    std::ofstream binFile(binFilename, std::ios::binary);
    if (!binFile) {
        std::cerr << "Failed to open output file.\n";
        return;
    }

    std::string name;
    int age;
    double salary;

    while (csv.read_row(name, age, salary)) {
        uint32_t len = static_cast<uint32_t>(name.size());
        binFile.write(reinterpret_cast<const char*>(&len), sizeof(len));
        binFile.write(name.data(), len);
        binFile.write(reinterpret_cast<const char*>(&age), sizeof(age));
        binFile.write(reinterpret_cast<const char*>(&salary), sizeof(salary));
    }

    // std::cout << "CSV -> BIN Successed.";
}

CSV_API void csvToBinStreaming(const std::string& csvPath, const std::string& binPath)
 {
    std::ifstream csvFile(csvPath);
    std::ofstream binFile(binPath, std::ios::binary);
    std::string line;

    // 读取表头
    std::getline(csvFile, line);
    std::stringstream ss(line);
    std::string cell;
    
    std::vector<std::string> headers;

    while (std::getline(ss, cell, ','))
    {
        headers.push_back(cell);
    }

    // 写入表头数量
    uint32_t headerCount = headers.size();
    binFile.write(reinterpret_cast<const char*>(&headerCount), sizeof(headerCount));

    // 写入每个表头（长度 + 内容）
    for (const auto& header : headers) {
        uint32_t len = static_cast<uint32_t>(header.size());
        binFile.write(reinterpret_cast<const char*>(&len), sizeof(len));
        binFile.write(header.c_str(), len);
    }

    // 写入每行数据（作为 double 存储）
    while (std::getline(csvFile, line)) {
        std::stringstream ssData(line);
        for (size_t i = 0; i < headerCount; ++i) {
            std::getline(ssData, cell, ',');
            double value = std::stod(cell);  // 注意错误处理
            binFile.write(reinterpret_cast<const char*>(&value), sizeof(value));
        }
    }

    std::cout << "CSV -> BIN done." << std::endl;
}

